// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.lang;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class PrintableInputStreamDecorator extends InputStream {

	public static InputStream build(InputStream input) {
		if (!(input instanceof PrintableInputStreamDecorator)) {
			try {
				return new PrintableInputStreamDecorator(input);
			}
			catch (IOException e) {
				throw new IllegalStateException(e);
			}
		}
		else {
			return input;
		}
	}

	private ByteArrayInputStream source;
	private int size;

	private PrintableInputStreamDecorator(InputStream source) throws IOException {
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		size = org.apache.commons.io.IOUtils.copy(source, data);
		this.source = new ByteArrayInputStream(data.toByteArray());
	}

	@Override
	public String toString() {
		return IOUtils.toStringAndReset(source, size);
	}

	@Override
	public int read() throws IOException {
		return source.read();
	}

	@Override
	public int read(byte[] b) throws IOException {
		return source.read(b);
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		return source.read(b, off, len);
	}

	@Override
	public long skip(long n) throws IOException {
		return source.skip(n);
	}

	@Override
	public int available() throws IOException {
		return source.available();
	}

	@Override
	public void close() throws IOException {
		source.close();
	}

	@Override
	public synchronized void mark(int readlimit) {
		source.mark(readlimit);
	}

	@Override
	public synchronized void reset() throws IOException {
		source.reset();
	}

	@Override
	public boolean markSupported() {
		return source.markSupported();
	}

}
